package net.mingsoft.expertmanage.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.mingsoft.expertmanage.dao.CompanyDao;
import net.mingsoft.expertmanage.entity.CompanyEntity;
import net.mingsoft.expertmanage.service.ICompanyService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 企业管理服务实现类
 */
@Service
public class CompanyServiceImpl extends ServiceImpl<CompanyDao, CompanyEntity> implements ICompanyService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importExcel(MultipartFile file) throws Exception {
        if (file == null || file.isEmpty()) {
            throw new Exception("请选择要导入的Excel文件");
        }
        
        String fileName = file.getOriginalFilename();
        if (fileName == null || !(fileName.endsWith(".xls") || fileName.endsWith(".xlsx"))) {
            throw new Exception("文件格式不正确，请上传Excel文件");
        }
        
        InputStream inputStream = file.getInputStream();
        List<CompanyEntity> companyList = new ArrayList<>();
        
        // 使用EasyExcel读取数据
        EasyExcel.read(inputStream, CompanyEntity.class, new PageReadListener<CompanyEntity>(dataList -> {
            for (CompanyEntity company : dataList) {
                if (StringUtils.isNotBlank(company.getCompanyCode())) {
                    companyList.add(company);
                }
            }
        })).sheet().doRead();
        
        if (companyList.isEmpty()) {
            return "Excel中没有有效数据";
        }
        
        // 批量保存数据
        this.saveBatch(companyList);
        
        return "成功导入" + companyList.size() + "条企业数据";
    }

    @Override
    public CompanyEntity getByCompanyCode(String companyCode) {
        if (StringUtils.isEmpty(companyCode)) {
            return null;
        }
        
        QueryWrapper<CompanyEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_code", companyCode);
        return this.getOne(queryWrapper);
    }

    @Override
    public List<CompanyEntity> searchByKeyword(String keyword) {
        QueryWrapper<CompanyEntity> queryWrapper = new QueryWrapper<>();
        
        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.like("company_code", keyword)
                     .or().like("company_name", keyword)
                     .or().like("business_keywords", keyword)
                     .or().like("required_tech_field", keyword);
        }
        
        return this.list(queryWrapper);
    }

    @Override
    public String extractCompanyCodeFromRelation(String relation) {
        if (StringUtils.isEmpty(relation)) {
            return null;
        }
        
        // 改进匹配模式，支持多种可能的表达形式
        // 如"关联企业库QY-001"、"企业QY-001"、"QY-001"、"QY001"等
        Pattern pattern = Pattern.compile("(QY[-]?\\d{3,})");
        Matcher matcher = pattern.matcher(relation);
        
        if (matcher.find()) {
            String found = matcher.group(1);
            // 标准化编号格式为QY-XXX
            if (!found.contains("-")) {
                found = found.substring(0, 2) + "-" + found.substring(2);
            }
            return found;
        }
        
        return null;
    }

    @Override
    public Integer getMaxSerialNo() {
        QueryWrapper<CompanyEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("MAX(serial_no) as serial_no");
        CompanyEntity company = this.getOne(queryWrapper);
        return company != null ? company.getSerialNo() : null;
    }

    @Override
    public List<CompanyEntity> getByExpertCode(String expertCode) {
        if (StringUtils.isEmpty(expertCode)) {
            return new ArrayList<>();
        }
        
        QueryWrapper<CompanyEntity> queryWrapper = new QueryWrapper<>();
        
        // 查找matched_expert_codes字段包含专家编号的记录
        // 使用 FIND_IN_SET 或 LIKE 查询，取决于数据格式
        queryWrapper.like("matched_expert_codes", expertCode)
                   .or()
                   .like("remarks", expertCode);
        
        return this.list(queryWrapper);
    }
} 